package leetcode.code0289;

import leetcode.IDebug;

public class Solution implements IDebug {

	int L2D = 0b01;
	int L2L = 0b11;
	int D2L = 0b10;

	int m, n;

	public void gameOfLife(int[][] board) {
		m = board.length;
		n = board[0].length;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				boolean live = board[i][j] == 1 ? true : false;
				int cur = this.f(board, i, j);
				if (live) {
					if (cur < 2) {
						board[i][j] = L2D;
					} else if (cur == 2 || cur == 3) {
						board[i][j] = L2L;
					} else {
						board[i][j] = L2D;
					}
				} else {
					if (cur == 3) {
						board[i][j] = D2L;
					}
				}
			}
		}
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				board[i][j] >>= 1;
			}
		}
	}

	private int f(int[][] board, int i, int j) {
		int ans = 0;
		ans += this.isLive(board, i - 1, j - 1);
		ans += this.isLive(board, i + 1, j + 1);
		ans += this.isLive(board, i + 1, j - 1);
		ans += this.isLive(board, i - 1, j + 1);
		ans += this.isLive(board, i + 1, j);
		ans += this.isLive(board, i, j + 1);
		ans += this.isLive(board, i - 1, j);
		ans += this.isLive(board, i, j - 1);
		return ans;
	}

	private int isLive(int[][] board, int i, int j) {
		if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] == 0 || board[i][j] == D2L) {
			return 0;
		}
		return 1;
	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
